
class SortedDictList(object):
    """
    builds a dict where the values a list of key value pairs.
    ex
    d = SortedDictList('#@')
    d['box'] = 'large'
    d['#apple'] = 1
    d['ax'] = 2
    d['@bag'] = 3

    {
        'a':{ '#apple':1, 'ax':2 },
        'b':{ 'box':'large', {'@bag':3 }
    }

    """
    def __init__(self, ignore_list=()):
        self._ignore_list = ignore_list
        self._data = {}

    def make_key(self, s):
        if type(s) == int:
            s = str(s)
        l = len(s)
        i = 0
        while i < l and s[i] in self._ignore_list:
            i += 1
        if i < l:
            return s[i].upper()
        else:
            return '?'

    def get_sorted_keys(self):
        keys = self._data.keys()
        keys.sort()
        return keys

    def get_sorted_names(self, key):
        if key in self._data:
            keys = self._data[key].keys()
            return sorted(keys, cmp=lambda x,y: cmp(x.lower(), y.lower()))
        else:
            return None
        
    def __contains__(self, name):
        key = self.make_key(name)
        if key in self._data:
            return name in self._data[key]
        else:
            return False

    def __getitem__(self, name):
        key = self.make_key(name)
        if key in self._data and name in self._data[key]:
            return self._data[key][name]
        else:
            raise KeyError

    def __setitem__(self, name, value):
        key = self.make_key(name)
        if key not in self._data:
            self._data[key] = {}
        self._data[key][name] = value


    def __len__(self):
        l = 0
        keys = self._data.keys()
        for i in keys:
            l += len(self._data[i])
        return l
